<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Serve;
use App\Models\Leimu;

use DB;
class ClassServeController extends Controller
{
       // 检测用户是否登录，无登录跳转到登录页面
    public function __construct()
    {
       $this->middleware('auth');
    }
    //类目展示页
    public function index(){

    	//取出已有服务列表
    	$serve = Serve::get();

    	$leimu = DB::table('class')->get();

    	$leimums = Leimu::get();

    	return view('staticpages.leimu.index',compact('serve','leimu','leimums'));
    }

    //添加类目
    public function store(Request $request){

    	//白名单数据
    	$data = $request->only(['cid','serve_a','created_at']);

    	//赋值当前时间戳
    	$data['created_at'] = date('Y-m-d H:i:s');

    	if(!in_array(null,$data)){

    		if($request->id != null){


				$num = count($request->id);

				if($num < 3 || $num > 4){

					return '最少选择3个服务，最多4个服务';exit;

				}else{

					$status = array();

					$cid = DB::table('class')->insertGetId(['classname'=>$request->classname]);

					foreach($request->id as $dv){

						$data['serve_a'] = $dv;
						$data['cid'] = $cid;

						$status[] = Leimu::insert($data);
					}

					if(!in_array(false, $status)){

						return back();
					}else{

						return '创建失败';
					}
				}
    			
    		}else{

    			return '请选择服务';exit;
    		}
    		
    	}else{

			return '请填写完整表单';exit;
    	}
    }

    //删除类目
    public function edit($id){

    	$status = Leimu::where('cid',$id)->delete();

    	if($status){

    		$sta = DB::table('class')->where('id',$id)->delete();

    		if($sta){

    			return back();
    		}else{

    			return '删除失败';
    		}
    	}else{

    		return '删除失败';
    	}
    }
}
